package com.bangcommunity.bbframe.dubbo.filter;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.support.RpcUtils;
import com.bangcommunity.bbframe.mlog.MLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by tanghc on 2016/4/7.
 */
@Activate(group = Constants.PROVIDER, order = 110)
public class MonitorProviderFilter implements Filter {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException {
        // logger.debug("========== monitor ==== dubbo provide ==========");
        // try {
        // Map<String, String> attachments = inv.getAttachments();
        // if (null != attachments) {
        // String requestInfo = attachments.get("requestInfo");
        // logger.debug("MonitorProviderFilter: requestInfo={}", requestInfo);
        // }
        // } catch (Exception e) {
        // logger.error("dubbo MonitorProviderFilter exception: " + e.getMessage());
        // }
        Result invoke = null;
        String service = invoker.getInterface().getSimpleName(); // 获取服务名称
        String method = RpcUtils.getMethodName(inv); // 获取方法名
        String key = new StringBuilder().append("dubboP").append("_").append(service).append("_").append(method)
                .toString();
        try {
            MLog.start(null, key, null, inv.getArguments());
            invoke = invoker.invoke(inv);
            if (invoke.hasException()) {
                MLog.exception(key, invoke.getException());
            } else {
                MLog.succ(key, null != invoke ? invoke.getValue() : null);
            }
        } catch (Exception e) {
            MLog.exception(key, e);
            throw e;
        }
        return invoke;
    }
}
